const pool = require('../db')
const app = require('./server')
// 路由
app.get('/api/news', function (req, res) {
    // res.setHeader('Access-Control-Allow-Origin','*')
    const page = req.query.page || 1;
    const size = req.query.page_size || 10
    pool.query({
        sql: 'select id,cate,title,source,pub_time from news where status =1 order by id desc limit ?,?',
        values: [(page - 1) * size, size]
    }, (err, result) => {
        if (err) {
            res.send({
                code: -1,
                message: '查询出错了,' + err.message
            })
        } else {
            res.send({
                code: 0,
                message: 'success',
                data: result
            })
        }
    })
})
app.get('/api/news/:id', (req, res) => {
    const id = req.params.id
    pool.query({
        sql: 'select * from  news where status=1 and id=?',
        values: [id]
    }, (err, result) => {
        if (err) {
            res.send({
                code: -1,
                message: '查询出错了',
                error: err.message
            })
        } else {
            if (result.length == 0) {
                res.send({
                    code: 2,
                    message: '没有找到要修改的新闻数据'
                })
            } else {
                res.send({
                    code: 0,
                    message: 'success',
                    data: result[0]
                })
            }
        }
    });
});
app.delete('/api/news/:id', (req, res) => {
    const id = req.params.id
    pool.query({
        sql: 'update news set status=0 where id=?',
        values: [id]
    }, (err) => {
        if (err) {
            res.send({
                code: -1,
                message: '删除出错了,' + err.message
            })
        } else {
            res.send({
                code: 0,
                message: 'success'
            })
        }
    })
});

app.post('/api/news', (req, res) => {
    const news = req.body;
    pool.query({
        sql: 'update news set title=?,cate=?,source=?,author=?,pub_time=?,content=? where id=?',
        values: [news.title, news.cate, news.source, news.author, news.pub_time, news.content, news.id]
    }, (err) => {
        if (err) {
            res.send({
                code: -1,
                message: '修改出错了,' + err.message
            })
        } else {
            res.send({
                code: 0,
                message: 'success'
            })
        }
    })
})